import { Controller, Get, Param, Req, Session } from '@nestjs/common';
import { ArticleViewsService } from './article-views.service';
import { EntityManager } from 'typeorm';
import { InjectEntityManager } from '@nestjs/typeorm';
import { User2 } from './entities/user2.entity';
import { Article2 } from './entities/article2.entity';

@Controller('article-views')
export class ArticleViewsController {
  constructor(private readonly articleViewsService: ArticleViewsService) {}

  @InjectEntityManager()
  private entityManager: EntityManager

  @Get('init-data')
  async initData() {
    await this.entityManager.save(User2, {
      username: 'abin',
      password: '111111'
    })
    await this.entityManager.save(User2, {
      username: 'abin2',
      password: '222222'
    })

    await this.entityManager.save(Article2, {
      title: '基于 Axios 封装一个完美的双 token 无感刷新',
      content: `用户登录之后，会返回一个用户的标识，之后带上这个标识请求别的接口，就能识别出该用户。

      标识登录状态的方案有两种： session 和 jwt。
      `
    })

    await this.entityManager.save(Article2, {
      title: 'Three.js 手写跳一跳小游戏',
      content: `前几年，跳一跳小游戏火过一段时间。

      玩家从一个方块跳到下一个方块，如果没跳过去就算失败，跳过去了就会再出现下一个方块。`
    });
    return 'done';
  }

  @Get(':id')
  async findOne(@Param('id') id: string) {
    return await this.articleViewsService.findOne(+id)
  }

  @Get(':id/view')
  async view(@Param('id') id: string, @Session() session, @Req() req) {
    return await this.articleViewsService.view(+id, session?.user?.userId || req.ip)
  }
}
